package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"zk/zg3_zk1/src/pro/appConfig"
	"zk/zg3_zk1/src/pro/global"
)

func InitMysql() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	data := appConfig.ConfigData.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		data.User, data.Passwd, data.Host, data.Port, data.Database)

	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(fmt.Sprintf("无法连接数据库: %v", err))
	} else {
		log.Println("数据库连接成功")
	}

	err = global.DB.AutoMigrate()
	if err != nil {
		panic("数据库迁移失败")
	} else {
		log.Println("数据库迁移成功")
	}
}
